package top.zhangjianyong.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.zhangjianyong.blog.cache.UserCache;
import top.zhangjianyong.blog.entity.po.Role;
import top.zhangjianyong.blog.entity.po.UserRole;
import top.zhangjianyong.blog.mapper.UserRoleMapper;
import top.zhangjianyong.blog.service.UserRoleService;

/**
 * 用户角色Service
 *
 * @author zhangjianyong
 * @since 2024/7/25 上午10:17
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements UserRoleService {

  private final UserRoleService userRoleService;

  public UserRoleServiceImpl(@Lazy UserRoleService userRoleService) {
    this.userRoleService = userRoleService;
  }

  @Override
  public boolean remove(Long id, Collection<Long> roleIds) {
    return CollectionUtils.isEmpty(roleIds)
        || lambdaUpdate().eq(UserRole::getUserId, id).in(UserRole::getRoleId, roleIds).remove();
  }

  @Override
  public boolean save(Long id, Collection<Long> roleIds) {
    if (CollectionUtils.isEmpty(roleIds)) return true;
    List<UserRole> userRoles =
        roleIds.stream()
            .map(
                role -> {
                  UserRole userRole = new UserRole();
                  userRole.setUserId(id);
                  userRole.setRoleId(role);
                  return userRole;
                })
            .collect(Collectors.toList());
    return userRoleService.saveBatch(userRoles);
  }

  @Override
  public List<Role> listByUserId(Long id) {
    MPJLambdaWrapper<UserRole> wrapper =
        new MPJLambdaWrapper<UserRole>()
            .selectAll(Role.class)
            .leftJoin(Role.class, Role::getId, UserRole::getRoleId)
            .eq(UserRole::getUserId, UserCache.userId());
    return baseMapper.selectJoinList(Role.class, wrapper);
  }

  @Override
  public boolean removeByUser(Long userId) {
    return lambdaUpdate().eq(UserRole::getUserId, userId).remove();
  }

  @Override
  public void removeByRole(Long roleId) {
    lambdaUpdate().eq(UserRole::getRoleId, roleId).remove();
  }
}
